package com.jn.algorithm.day006.question19;

/**
 * @author 江南大学1033190417
 * @date 2022/4/20 14:54
 */
public class Solution {
    public ListNode removeNthFromEnd(ListNode head, int n) {
        if (head == null) {
            return null;
        }
        int count = 0;//个数
        ListNode node = head;
        while (node != null) {
            count++;
            node = node.next;
        }
        int get=count-n;//找到要删除的
        if (get==0){//如果删除的是第一个
            head=head.next;
            return head;
        }
        node=head;
        int num=0;
        while (node!=null){
            if (num==get-1){
                node.next=node.next.next;
                break;
            }
            num++;
            node=node.next;
        }
        return head;
    }

    public static void main(String[] args) {
        Solution solution = new Solution();
        ListNode head=new ListNode(1);
//        head.next=new ListNode(2);
//        head.next.next=new ListNode(3);
//        head.next.next.next=new ListNode(4);
//        head.next.next.next.next=new ListNode(5);
        System.out.println(solution.removeNthFromEnd(head, 1));
    }
}

class ListNode {
    int val;
    ListNode next;

    ListNode() {
    }

    ListNode(int val) {
        this.val = val;
    }

    ListNode(int val, ListNode next) {
        this.val = val;
        this.next = next;
    }
}
